<!DOCTYPE html>
<html>
    <head>
      <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    </head>
<body>
  
  <div class="container">
  <h1>IR Controller</h1>

<p>
<input type="button" class="btn btn-primary btn-lg" id="button" value="Connect" onclick="connect(); return false;" />
<input type="button" id="read_sensors" class="btn btn-primary btn-lg" value="read sensors" onclick="read_sensors(); return false;" />
<span class="btn-lg">Temperature: <span id="temp"></span>°C humidity: <span id="humid"></span>%</span></p>
<p>
<input type="button" id="aircon_on" class="btn btn-primary btn-lg" value="Air Conditioner On" onclick="send_ir_command(0); return false;" />
<input type="button" id="aircon_off" class="btn btn-primary btn-lg" value="Air Conditioner Off" onclick="send_ir_command(2); return false;" />
</p>
<p>
<input type="button" id="TV_on" class="btn btn-primary btn-lg" value="TV On" onclick="send_ir_command(1); return false;" />
</p>

</div>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

<script>
var ws;
var event_data;

function connect(){
    // change the address to global IP
    ws = new WebSocket("ws://192.168.0.6:6578/");
    ws.binaryType = 'arraybuffer';

    ws.onmessage = function(event) {
        console.log(event);
        event_data = event;
        if (event.data instanceof ArrayBuffer) {
            var data = new Uint8Array(event.data);
            if(data[0] == 100){
                var temp, humid;
                temp = (data[2] * 256 + data[3]) * 0.1;
                humid = (data[4] * 256 + data[5]) * 0.1;
                $("#temp").text(temp.toFixed(1));
                $("#humid").text(humid.toFixed(1));
                console.log([temp, humid])
            }
            console.log(data);
        }
    }
}

function read_sensors(){
    var data = new Uint8Array(1);
    data[0] = 100;
    ws.send(data);
}

function send_ir_command(cmd){
    var data = new Uint8Array(2);
    data[0] = 200;
    data[1] = cmd;
    ws.send(data);
}

</script>
</body>
</html>
